# -*- coding: utf-8 -*-
"""
Web framework/Tornado RequestHandler Class/test02.py
"""

import tornado.web
import asyncio


class IndexHandler(tornado.web.RequestHandler):
    def initialize(self) -> None:
        print("This is initialize function.")
        # Case 03:
        # self.finish("This is initialize Result.")
        # > curl http://127.0.0.1:8888/id/333
        # > TypeError: 'NoneType' object is not iterable

    def prepare(self):
        if '123' in self.path_args:
            m_message = "This is prepare function error."
            self.finish(m_message)
            print(m_message)
            # Case 02:
            # > curl http://127.0.0.1:8888/id/123
            # > This is initialize function.
            # > This is prepare function error.
            # > This is prepare function.
        elif '1234' in self.path_args:
            m_message = "This is prepare function write."
            self.write(m_message)
            print(m_message)
            # Case 04:
            # > curl http://127.0.0.1:8888/id/1234
            # > This is initialize function.
            # > This is prepare function write.
            # > This is prepare function.
            # > This is get method. $1234

        print("This is prepare function.")

    def get(self, id):
        m_result = f'This is get method. ${id}'
        print(m_result)
        return self.write(m_result)


async def main():
    app = tornado.web.Application(handlers=[
        ("/id/([^/]+)", IndexHandler)
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == "__main__":
    asyncio.run(main())

# Case 01:
# > curl http://127.0.0.1:8888/id/13
# > This is initialize function.
# > This is prepare function.
# > This is get method. $13
